function fit(el, ratio, areaW, areaH, mode = 'fit', isForcedTop = false) {
	// fit <video> or <img> in certain range / fullscreen
	// fit(img, 400/267, w, h);
	let x = 0;
	let y = 0;
	let vw = 0;
	let vh = 0;
	const aw = areaW || window.innerWidth;
	const ah = areaH || window.innerHeight;

	if (mode == 'center') {
		// it never crops the visual
		if (ratio <= aw / ah) {
			vh = ah;
			vw = Math.round(ah * ratio);
			y = 0;
			x = parseInt((aw - vw) / 2);
		} else {
			vw = aw;
			vh = Math.round(aw / ratio);
			y = parseInt((ah - vh) / 2);
			x = 0;
		}
	} else {
		// fit, it will crop the visual
		if (ratio <= aw / ah) {
			vw = aw;
			vh = Math.round(aw / ratio);
			y = -parseInt((vh - ah) / 2);
			x = 0;
		} else {
			vw = Math.round(ah * ratio);
			vh = ah;
			y = 0;
			x = -parseInt((vw - aw) / 2);
		}
	}

	el.style.position = 'absolute';
	el.style.width = `${vw}px`;
	el.style.height = `${vh}px`;
	el.style.left = `${x}px`;
	el.style.top = `${isForcedTop == true ? 0 : y}px`;
}

function fitFontSize(el, compressor = 6, min = 0, max = 999999) {
	const width = el.getBoundingClientRect().width;
	// console.log(width, el.offsetWidth);

	let size;
	size = Math.max(
		Math.min(width / compressor, parseFloat(Number.POSITIVE_INFINITY)),
		parseFloat(Number.NEGATIVE_INFINITY)
	);
	size = Math.max(min, Math.min(parseInt(size), max));
	el.style.fontSize = `${size}px`;
	el.style.lineHeight = `${size}px`;
}

function fitBackground(el, ratio, maxWidth = 999999, originX = 50, originY = 50) {
	// resize background image in an element
	// const div = document.createElement('div');
	// div.style.position        = 'absolute';
	// div.style.backgroundColor = '#ff9900';
	// div.style.backgroundImage = 'url('+ src +')';
	// div.style.left            = '50px';
	// div.style.top             = '250px';
	// div.style.width           = '500px';
	// div.style.height          = '200px';
	// document.body.appendChild(div);

	// fitBackground(div, 400/267);

	const width = el.getBoundingClientRect().width;
	const height = el.getBoundingClientRect().height;
	// console.log(width, el.offsetWidth);

	// getComputedStyle
	const css = window.getComputedStyle(el);
	const aw = width + parseInt(css['padding-left']) + parseInt(css['padding-right']);
	const ah = height + parseInt(css['padding-top']) + parseInt(css['padding-bottom']);
	let vw;
	let vh;

	if (ratio > aw / ah) {
		vw = parseInt(ah * ratio);
		vh = ah;
	} else {
		vw = aw;
		vh = parseInt(aw / ratio);
	}

	if (vw > maxWidth) {
		vw = maxWidth;
		vh = parseInt(maxWidth / ratio);
	}

	el.style.backgroundSize = `${vw}px ${vh}px`;
	el.style.backgroundPosition = `${originX}% ${originY}%`;
	el.style.backgroundRepeat = 'no-repeat';
}

export { fit, fitFontSize, fitBackground };
